package chatv2.client;

import java.io.File;
import java.io.FileNotFoundException;
import java.rmi.RemoteException;
import chatv2.server.ChatServerAppInterface;
import rmioverlay.client.ClientApp;

public class ChatClientApp extends ClientApp<ChatServerAppInterface> implements ChatClientAppInterface {
	private static final long serialVersionUID = 3349419367636876622L;
	private GUI gui;
	
	protected ChatClientApp(GUI pGUI) throws RemoteException {
		super();
		this.gui = pGUI;
	}

	public <T>void receive(T pData) {
		if (pData instanceof File) {
			this.gui.appendChat("Received file "+((File)pData).getAbsolutePath());
		}
		else {
			String s = pData.toString();
			String[] tab = s.split(" ");
			
			if (tab[1].equals("vous")) {
				WhisperTab t = (WhisperTab) this.gui.getTab(tab[0]);
				if (t == null)
					this.gui.newTab(this, this.gui, tab[0]).appendChatWhisper(s);
				else
					t.appendChatWhisper(s);
			}
			else {
				this.gui.appendChat(s);
			}
		}
	}

	public void sendAll(String pMsg)
			throws RemoteException {
		try {
			this.getServer().<String>sendAll(pMsg);
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public <T>void send(String pLogin, T pData)
			throws RemoteException, FileNotFoundException {
		if (pData instanceof File) {
			File f = (File)pData;
			this.<String>receive("Sending file "+f.getName()+" to "+pLogin);
			this.<String>send(pLogin, "Receiving file "+f.getName()+" from "+this.gui.getLogin());
		}
		super.<T>send(pLogin, pData);
	}
	
	public <T>void sendAll(T pData)
			throws RemoteException, FileNotFoundException {
		if (pData instanceof File) {
			File f = (File)pData;
			this.<String>sendAll("Receiving file "+f.getName()+" from "+this.gui.getLogin());
		}
		super.<T>sendAll(pData);
	}
}
